<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;

/**
 * 会员中心
 */
class User extends Frontend
{
    protected $layout = 'default';
    protected $noNeedLogin = ['login', 'register', 'third'];
    protected $noNeedRight = ['*'];

    protected $isanchanguser = false; //案場客戶, 仅关联一个案场

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });

        $this->adminuser = \app\admin\model\Admin::where('username', $this->auth->username)->find();

        $this->groupIds = [];
        if ($this->adminuser) {
            $agalist = \app\admin\model\AuthGroupAccess::where('uid', $this->adminuser->id)->select();
            foreach ($agalist as $row) {
                $this->groupIds[] = $row->group_id;
            }
        } else {
            //没有关联账号则重新注册
            $user = $this->auth->getUser();
            if ($user) {
                $admin = new \app\admin\model\Admin();
                $admin->username = $user->username;
                $admin->nickname = $user->username;
                $admin->email = $user->email;
                $admin->phone = $user->mobile;
                $admin->salt = $user->salt;
                $admin->password = $user->password;
                $admin->avatar = '/assets/img/avatar.png'; //设置新管理员默认头像。
                $admin->remark = $user->bio;
                $admin->save();
                $this->adminuser = $admin;

                $aga = new \app\admin\model\AuthGroupAccess();
                $aga->uid = $admin->id;
                $aga->group_id = 11;//未開通帳號
                $aga->save();
            }
        }

        if (in_array("2", $this->groupIds) || in_array("1", $this->groupIds)) {
            $this->isadmin = true;//管理员权限不考虑管辖区域
        }

        if (in_array("5", $this->groupIds) || in_array("9", $this->groupIds)) {
            $this->isanchanguser = true;//案場客戶, 仅关联一个案场
        }

        $this->view->assign("isanchanguser", $this->isanchanguser);

        $anchangname = "";
        $anchangid = 0;
        if ($this->isanchanguser) {
            $anchangidlist = json_decode($this->adminuser['anchangids'], TRUE);
            if (count($anchangidlist) > 0) {
                $anchangid = $anchangidlist[0]['id'];
                $anchang = \app\admin\model\jdy\Anchang::get($anchangid);
                if ($anchang) {
                    $anchangname = $anchang->name;
                }
            }
        }

        $this->view->assign("anchangname", $anchangname);
        $this->view->assign("anchangid", $anchangid);
    }

    /**
     * 空的请求
     * @param $name
     * @return mixed
     */
    public function _empty($name)
    {
        $data = Hook::listen("user_request_empty", $name);
        foreach ($data as $index => $datum) {
            $this->view->assign($datum);
        }
        return $this->view->fetch('user/' . $name);
    }

    /**
     * 会员中心
     */
    //http://acciot.test/index/user/
    public function index()
    {
        $this->view->assign('title', __('User center'));
        return $this->view->fetch();
    }

    /**
     * 注册会员
     */
    public function register()
    {
        $url = $this->request->request('url');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        }
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $email = $this->request->post('email');
            $mobile = $this->request->post('mobile', '');
            $bio = $this->request->post('bio');
            $captcha = $this->request->post('captcha');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,30',
                'email'     => 'require|email',
//                'mobile'    => 'regex:/^1\d{10}$/', // ^(\+?0?86\-?)?1[345789]\d{9}$
            //0960123456
//                'mobile'    => 'regex:/^9\d{8}$/', // ^(\+?886\-?|0)?9\d{8}$
                'captcha'   => 'require|captcha',
                '__token__' => 'token',
            ];

            $msg = [
                'username.require' => 'Username can not be empty',
                'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
                'captcha.require'  => 'Captcha can not be empty',
                'captcha.captcha'  => 'Captcha is incorrect',
                'email'            => 'Email is incorrect',
//                'mobile'           => 'Mobile is incorrect',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                'email'     => $email,
                'mobile'    => $mobile,
                'captcha'   => $captcha,
                'bio'    => $bio,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            if ($this->auth->register($username, $password, $email, $mobile)) {

                $user = $this->auth->getUser();
                if ($user) {
                    $admin = new \app\admin\model\Admin();
                    $admin->username = $username;
                    $admin->nickname = $username;
                    $admin->email = $email;
                    $admin->phone = $mobile;
                    $admin->salt = $user->salt;
                    $admin->password = $user->password;
                    $admin->avatar = '/assets/img/avatar.png'; //设置新管理员默认头像。
                    $admin->remark = $bio;
                    $admin->save();

                    $aga = new \app\admin\model\AuthGroupAccess();
                    $aga->uid = $admin->id;
                    $aga->group_id = 11;//未開通帳號
                    $aga->save();
                }

                //http://acciot.test/index/user/login.html
                $url = 'http://'.$_SERVER['HTTP_HOST'];

                $link = "http://" . $_SERVER['HTTP_HOST'] . "/admin/auth/admin?ref=addtabs";
                $news = new \app\admin\model\jdy\News();
                $news->name = "新用戶註冊->" . $username;
                $news->link = $link;
                $news->save();

                $this->success(__('Sign up successful'), $url);
//                $this->success(__('Sign up successful'), $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch();
    }

    /**
     * 会员登录
     */
    //http://acciot.test/index/user/login.html
    public function login()
    {
//        $url = $this->request->request('url');
        $url = "";
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('home/index'));
        }
        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $password = $this->request->post('password');
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'account'   => 'require|length:3,50',
                'password'  => 'require|length:6,30',
                '__token__' => 'token',
            ];

            $msg = [
                'account.require'  => 'Account can not be empty',
                'account.length'   => 'Account must be 3 to 50 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
            ];
            $data = [
                'account'   => $account,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }
            if ($this->auth->login($account, $password)) {
                $this->success(__('Logged in successful'), $url ? $url : url('home/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Login'));
        return $this->view->fetch();
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        //注销本站
        $this->auth->logout();
        $this->success(__('Logout successful'), url('user/index'));
    }

    protected $adminuser = null;//关联的admin账号
    protected $groupIds = []; //admin账号关联的角色组fa_auth_group
    /**
     * 个人信息
     */
    public function profile()
    {
        $this->adminuser = \app\admin\model\Admin::where('username', $this->auth->username)->find();

        $this->groupIds = [];
        if ($this->adminuser) {
            $agalist = \app\admin\model\AuthGroupAccess::where('uid', $this->adminuser->id)->select();
            foreach ($agalist as $row) {
                $this->groupIds[] = $row->group_id;
            }
        } else {
            //没有关联账号则重新注册
            $user = $this->auth->getUser();
            if ($user) {
                $admin = new \app\admin\model\Admin();
                $admin->username = $user->username;
                $admin->nickname = $user->username;
                $admin->email = $user->email;
                $admin->phone = $user->mobile;
                $admin->salt = $user->salt;
                $admin->password = $user->password;
                $admin->avatar = '/assets/img/avatar.png'; //设置新管理员默认头像。
                $admin->remark = $user->bio;
                $admin->save();
                $this->adminuser = $admin;

                $aga = new \app\admin\model\AuthGroupAccess();
                $aga->uid = $admin->id;
                $aga->group_id = 11;//未開通帳號
                $aga->save();
            }
        }

        $quyu = $this->adminuser['xianshi1'].$this->adminuser['xzq1'];
        $quyu .= " ".$this->adminuser['xianshi2'].$this->adminuser['xzq2'];
        $quyu .= " ".$this->adminuser['xianshi3'].$this->adminuser['xzq3'];
        $quyu .= " ".$this->adminuser['xianshi4'].$this->adminuser['xzq4'];
        $quyu .= " ".$this->adminuser['xianshi5'].$this->adminuser['xzq5'];

        $this->view->assign('quyu', $quyu);
        $this->view->assign('title', __('Profile'));
        return $this->view->fetch();
    }

    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword'   => 'require|length:6,30',
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__'     => $token,
            ];
            $field = [
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $this->success(__('Reset password successful'), url('user/login'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('title', __('Change password'));
        return $this->view->fetch();
    }
}
